package com.yonyou.brigade.third_parties.ctrip.bigcustomer.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.model.CtripBigUser;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.dao.CtripBigUserMapper;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.service.ICtripBigUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.util.EmployeeSyncUtils;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.util.UserConvert;
import com.yonyou.brigade.third_parties.ctrip.model.CtripConfig;
import com.yonyou.brigade.third_parties.third.model.BriDeptAuthorization;
import com.yonyou.brigade.third_parties.third.model.BriThirdProperty;
import com.yonyou.brigade.third_parties.third.service.IBriGroupMemberService;
import com.yonyou.brigade.third_parties.third.service.IBriThirdPropertyService;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import corp.openapicalls.contract.employee.AuthenticationListRequst;
import corp.openapicalls.contract.ordercontroller.ticket.OrderSearchTicketResponse;
import corp.openapicalls.service.ticket.CorpTicketService;
import org.apache.commons.collections4.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangzhf@yonyou.com
 * @since 2018-08-17
 */
@Service
public class CtripBigUserServiceImpl extends ServiceImpl<CtripBigUserMapper, CtripBigUser> implements ICtripBigUserService {

    @Autowired
    private CtripBigUserMapper ctripBigUserMapper;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("briThirdPropertyServiceImpl")
    private IBriThirdPropertyService briThirdPropertyService;

    @Autowired
    @Qualifier("briGroupMemberServiceImpl")
    private IBriGroupMemberService groupMemberService;



    private Logger logger=LoggerFactory.getLogger(CtripBigUserServiceImpl.class);

    public List<CtripBigUser> findNeedAsynUsersByListAuth(List<String> userIds)
    {
        return  ctripBigUserMapper.findNeedAsynUsersByListAuth(userIds);
    }

    public   List<CtripBigUser> findCtripUserListForUpdate(List<String> userIds)
    {
        return  ctripBigUserMapper.findCtripUserListForUpdate(userIds);
    }

    @Override
    public void insertCtripUserBatch(List<CtripBigUser> ctripUsers) {
        if(!ctripUsers.isEmpty()){
            ctripBigUserMapper.insertCtripUserBatch(ctripUsers);
        }
    }
    public List<String> selectUserIdByDept(List<String> list)
    {
        return  ctripBigUserMapper.selectUserIdByDept(list);
    }

    public List<CtripBigUser> findNoSyncBigUser(Map params)
    {
        return  ctripBigUserMapper.findNoSyncBigUser(params);
    }

    public void syncCtripBigUsers(String tenant,String orgPk,List<UcUserDto> ucUserDtos)
    {
        List<CtripBigUser> needAsyCtripBigUser=new ArrayList<>();
        CtripConfig config=new CtripConfig();
        CtripConfig ctripConfig=(CtripConfig) briChannelService.getChannelConfig(tenant,ChannelEnum.CTRIPBC.getName(),config);
        Map thirdPropertyParams=new HashMap();
        thirdPropertyParams.put("channel",ChannelEnum.CTRIPBC.getName());
        thirdPropertyParams.put("tenant",tenant);
        thirdPropertyParams.put("orgPk",orgPk);
        List<BriThirdProperty> briThirdProperties=  briThirdPropertyService.findPropsByChannel(thirdPropertyParams);
        if(briThirdProperties==null||briThirdProperties.size()==0)
        {
            initDefaultCtripBCProperties(tenant,orgPk);
        }
        //已同步的用户
        logger.info(tenant+"开始查找已经同步过的携程用户");
        Wrapper<CtripBigUser> wrapper = new EntityWrapper<>();
        wrapper.eq("tenant",tenant);
        wrapper.eq("org_pk",orgPk);
        List<CtripBigUser> ctripBigUsers1 = this.baseMapper.selectList(wrapper);
        Set<String> alreadyHasUserids = new HashSet<>();
        if (ctripBigUsers1 != null && ctripBigUsers1.size() > 0){
            ctripBigUsers1.forEach(rtpnrUser -> {
                alreadyHasUserids.add(rtpnrUser.getUserId());
            });
        }
        logger.info(tenant+"已经同步过的携程用户为"+alreadyHasUserids.size());

        ucUserDtos.forEach(ucUserDto -> {
            //只处理未同步的用户
            if (!alreadyHasUserids.contains(ucUserDto.getUserId())){
                CtripBigUser ctripBigUser=UserConvert.convertToSingleCtripBigUser(ucUserDto,orgPk,tenant);
                needAsyCtripBigUser.add(ctripBigUser);
            }
        });
        logger.info(tenant+"需要同步携程用户为"+alreadyHasUserids.size());
        logger.info("开始拼装用户信息");
        syncCtripBigUsers(needAsyCtripBigUser,ctripConfig,briThirdProperties);
    }

    public void syncCtripBigUsers(String tenant,String orgPk)
    {
        logger.info("begin async ctrip user, tenant="+tenant+", orgPK="+orgPk);
        List<UcUserDto>  ucUserDtos= userCenterService.getUcUserDtoByOrg(tenant,orgPk);
        List<CtripBigUser> ctripBigUsers=UserConvert.convertToCtripBigUser(ucUserDtos,orgPk,tenant);
        logger.info("after convert ctripBigUsers:");
        if(ctripBigUsers!=null&&ctripBigUsers.size()>0)
        {
            for(int i=0;i<ctripBigUsers.size();i++)
            {
                logger.info(ctripBigUsers.get(i).toString());
            }
        }
        CtripConfig config=new CtripConfig();
        CtripConfig ctripConfig=(CtripConfig) briChannelService.getChannelConfig(tenant,ChannelEnum.CTRIPBC.getName(),config);
        Map thirdPropertyParams=new HashMap();
        thirdPropertyParams.put("channel",ChannelEnum.CTRIPBC.getName());
        thirdPropertyParams.put("tenant",tenant);
        thirdPropertyParams.put("orgPk",orgPk);
        List<BriThirdProperty> briThirdProperties=  briThirdPropertyService.findPropsByChannel(thirdPropertyParams);
        syncCtripBigUsers(ctripBigUsers,ctripConfig,briThirdProperties);
    }

    /**
     *
     * @Title: multipleEmployeeSync
     * @Description: 批量人事更新
     * @param
     * @return void    返回类型
     * @throws
     */
    public  void syncCtripBigUsers(List<CtripBigUser> ctripUsers, CtripConfig ctripMaster, List<BriThirdProperty> thirdProperties){

        List<CtripBigUser> ctripBigUsers=new ArrayList<>();
        if(ctripUsers!=null&&ctripUsers.size()>0) {
            for(int i=0;i<ctripUsers.size();i++) {
                Wrapper<CtripBigUser> ctripBigUserWrapper = new EntityWrapper<>();
                ctripBigUserWrapper.where("1={0}", 1);
                ctripBigUserWrapper.and("user_id={0}", ctripUsers.get(i).getUserId());
                List<CtripBigUser> bigUsers = ctripBigUserMapper.selectList(ctripBigUserWrapper);
                if (bigUsers != null && bigUsers.size() != 0) {
                    continue;
                } else {
                    ctripBigUsers.add(ctripUsers.get(i));
                    logger.info("新增用户信息： " + ctripUsers.get(i).toString());
                }
            }
        }

        if(ctripBigUsers.size()==0)
        {
            return;
        }

        OrderSearchTicketResponse ticketResponse= CorpTicketService.getEmployeeSyncTicket(ctripMaster.getAppKey(), ctripMaster.getAppSecurity(), "1.0");
        if(ticketResponse!=null&&ticketResponse.getStatus()!=null&&ticketResponse.getStatus().getSuccess())
        {
            List<BriDeptAuthorization> deptAuths=new ArrayList<>();
            logger.info("get ticket success! ticket:"+ticketResponse.getTicket());
            AuthenticationListRequst authenticationListRequst = null;
            List<List<CtripBigUser>> lists = ListUtils.partition(ctripBigUsers, 500);
            for (List<CtripBigUser> ctripUserBatch : lists) {
                authenticationListRequst = EmployeeSyncUtils.buildAuthenticationListRequst(ticketResponse.getTicket(), ctripUserBatch, ctripMaster,deptAuths,false,thirdProperties);
                boolean success= EmployeeSyncUtils.multipleUsersSync(authenticationListRequst);
                if(success)
                {
                   //Wrapper<CtripBigUser> ctripBigUserWrapper=new EntityWrapper<>();
                   //ctripBigUserWrapper.where("1={0}",1);
                   //List<CtripBigUser> ctripBigUsers=  ctripBigUserMapper.selectList(ctripBigUserWrapper);
                   logger.info("开始向本地同步用户");
                   for(int m=0;m<ctripUserBatch.size();m++)
                   {
                       Wrapper<CtripBigUser> ctripBigUserWrapper=new EntityWrapper<>();
                       ctripBigUserWrapper.where("1={0}",1);
                       ctripBigUserWrapper.and("user_id={0}", ctripUserBatch.get(m).getUserId());
                       List<CtripBigUser> bigUsers=  ctripBigUserMapper.selectList(ctripBigUserWrapper);
                       if(bigUsers != null && bigUsers.size() != 0){
                           continue;
                       }else {
                           ctripBigUserMapper.insert(ctripUserBatch.get(m));
                           logger.info("新增用户信息： " + ctripUserBatch.get(m).getPhone());
                       }
                   }
                }
                else
                {
                    logger.error("同步携程用户失败");
                }
            }
        }
        else{
            String errorms = String.format("get ticket failed! error message:%s", JSON.toJSONString(ticketResponse));
            logger.info("get ticket failed! error message:%s", JSON.toJSONString(ticketResponse));
            throw new RuntimeException(errorms);
        }
    }

    private BriThirdProperty wrapperThirdProperty(String key,String value,String type,String tenant,String channel,String orgPk)
    {
        BriThirdProperty briThirdProperty=new BriThirdProperty();
        briThirdProperty.setChannel(channel);
        briThirdProperty.setTenant(tenant);
        briThirdProperty.setOrgPk(orgPk);
        briThirdProperty.setKey(key);
        briThirdProperty.setType(value);
        briThirdProperty.setValue(type);
        return  briThirdProperty;
    }

    private List<BriThirdProperty> initDefaultCtripBCProperties(String tenant,String orgPk)
    {
        List<BriThirdProperty> briThirdProperties=new ArrayList<>();
        briThirdProperties.add(wrapperThirdProperty("CorpCardType","B","String",tenant,ChannelEnum.CTRIPBC.getName(),orgPk));
        briThirdProperties.add(wrapperThirdProperty("ResRange","C","String",tenant,ChannelEnum.CTRIPBC.getName(),orgPk));
        briThirdProperties.add(wrapperThirdProperty("UseTRFlag","31","INTEGER",tenant,ChannelEnum.CTRIPBC.getName(),orgPk));
        return briThirdProperties;

    }
}
